<?php
namespace App\Repositories\BLL;
use App\Repositories\BLL\Repository;
use App\Models\Admins\Permission;
use Illuminate\Support\Facades\DB;

class PermissionBLL extends Repository
{
	public function model()
	{
		return Permission::class;
	}
	
	public function ajaxIndex($currentRouteName)
	{
		// datatables请求次数
	    	$draw = request('draw', 1);
	    	// 开始条数
		$start = request('start',config('admin.global.list.start'));
		// 每页显示数目
		$length = request('length',config('admin.global.list.length'));
		// 排序
	    $order['name'] = request('columns.' .request('order.0.column',0) . '.name');
	    $order['dir'] = request('order.0.dir','asc');

	    $search['value'] = request('search.value','');

	    $search['regex'] = request('search.regex',false);

	    $permission = $this->model;

	    // 搜索框中的值
	    if ($search['value']) {
	        if($search['regex'] == 'true'){
	            $permission = $permission->where('name', 'like', "%{$search['value']}%")->orWhere('display_name','like', "%{$search['value']}%");
	        }else{
	            $permission = $permission->where('name', $search['value'])->orWhere('display_name', $search['value']);
	        }
	    }

	    $count = $permission->count();

	    $permission = $permission->orderBy($order['name'], $order['dir']);
    		$permissions = $permission->offset($start)->limit($length)->get();
		
	  	//获取当前路由
		if ($permissions) {
			foreach ($permissions as &$v) {
				$v->actionButton = $v->getListActionButton($currentRouteName);
			}
		}

	    	//datatables固定返回格式
	    	return [
	        'draw' => $draw,
	        'recordsTotal' => $count,
	        'recordsFiltered' => $count,
	        'data' => $permissions,
	    ];
	}

	public function createPermission($attributes)
	{
		$result = $this->create($attributes);
		if ($result) {
			flash('添加权限成功');
		}else{
			flash('添加权限失败','error');
		}
		return $result;
	}
	
	public function editView($id)
	{
		$permission = $this->find($id);
		if ($permission) {
			return $permission;
		}
		abort(404);
	}

	public function updatePermission($attributes)
	{
		$result = $this->update($attributes,$attributes['id']);
		if ($result) {
			flash('修改权限成功');
		}else{
			flash('修改权限失败','error');
		}
		return $result;
	}

	public function destroyPermission($id)
	{
		$result = $this->delete($id);
		if ($result) {
			flash('修改权限成功');
		}else{
			flash('修改权限失败','error');
		}
		return $result;
	}
	
	public function getAllPermissionMenu(){
		$result = DB::table('permissions')
            ->leftJoin('menus', 'permissions.name', '=', 'menus.permission')
			->select('menus.level','permissions.id','permissions.display_name',DB::raw('IFNULL(menus.id,CONCAT("p",permissions.id)) menuid,IFNULL(menus.pid,999) as menupid'))
			->orderBy(DB::raw('IFNULL(menus.level,999)'))
			->orderBy('menus.pid')
			->orderBy('menus.sort', 'desc')
            ->get();
		return $result;
	}
}